<template>
    <zt-dialog v-model="visible" :title="props.objectValue.roleName + ' 授权分配菜单'" @confirm="confirmBtn" :loading="isLoading"
        :showFooter="true" :showFullScreen="false" width="800px" height="600px" :showConfirm="true">
        <el-tree ref="treeRef" :data="menuList" show-checkbox highlight-current node-key="menuId"
            :default-expanded-keys="expandedKeys" :default-selected-keys="selectedKeys" :default-checked-keys="checkedKeys"
            :props="defaultProps" />
    </zt-dialog>
</template>

<script  setup>
import ztDialog from '@/components/zt-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { apiGetMenuTree } from "@/api/common/api.js";
import { apiGetRoleMenu, apiPutRoleEmpower } from "@/api/admin/systemSettings/rolesManage/api.js";
const isLoading = ref(false)
const treeRef = ref(null)
const emit = defineEmits(['success', 'update:modelValue'])
const props = defineProps({
    // 控制弹窗显示
    visible: {
        type: Boolean,
        default: false
    },
    // 传递过来的值
    objectValue: {
        type: Object,
        default: () => {
            return {}
        }
    }
})
// 子组件定义自己的visible
const visible = computed({
    get: () => props.visible,
    set: (value) => {
        emit('update:modelValue', value)
    },
})
const defaultProps = {
    children: 'childrenMenus',
    label: 'name',
}


// 确认按钮
async function confirmBtn() {
    let menuIds = treeRef.value.getCheckedKeys(true) //获取选中的菜单id
    let arrs = []
    // 此处为循环去拿取 根据当前子级的数据 获取对应父级的id
    menuIds.forEach(item => {
        arrs.push(...getAllParentValues(menuList.value, item))
    })
    let newArrs = [...new Set(arrs)]//此处为去重

    isLoading.value = true
    apiPutRoleEmpower({
        roleId: props.objectValue.roleId,
        menuIds: newArrs.join(','),
    }).then(res => {
        isLoading.value = false
        if (res.success) {
            ElMessage({
                message: '授权成功',
                type: 'success',
            })
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    })
}

const menuList = ref([])
const checkedKeys = ref([])
// 获取已分配的菜单列表数据
async function getMenuList() {
    isLoading.value = true
    await apiGetMenuTree().then(res => {
        isLoading.value = false
        if (res.success) {
            menuList.value = mergeButtonsToChildren(res.data)
        }
    })

    await apiGetRoleMenu({ roleId: props.objectValue.roleId }).then(res => {
        if (res.success) {
            let arrs = []
            // 数据处理值 把父级的menuId 去掉  因为会导致全部选中的问题
            res.data.forEach(item => {
                if (findMenuIdInChildrenMenus(menuList.value, item)) {
                    arrs.push(findMenuIdInChildrenMenus(menuList.value, item))
                }
            })
            let newArrs = [...new Set(arrs)]//此处为去重
            checkedKeys.value = newArrs
        }
    })
}

// 只获取到childrenMenus的menuId 
function findMenuIdInChildrenMenus(childrenMenus, targetId) {
    for (let i = 0; i < childrenMenus.length; i++) {
        const item = childrenMenus[i];

        if (item.menuId === targetId && !item.childrenMenus) {
            return item.menuId;
        }
        // 判断没有子菜单也没有按钮
        if (item.menuId === targetId && item.buttons && item.buttons.length == 0 && item.childrenMenus && item.childrenMenus.length == 0) {
            return item.menuId;
        }



        if (item.childrenMenus && item.childrenMenus.length > 0) {
            const foundMenuId = findMenuIdInChildrenMenus(item.childrenMenus, targetId);
            if (foundMenuId !== null) {
                // console.log('foundMenuId', foundMenuId)
                return foundMenuId;
            }
        }
    }
    return null;
}


// 数据处理 从最里面遍历拿取
function getAllParentValues(arrs, menuId) {
    for (let i = 0; i < arrs.length; i++) {
        const item = arrs[i];
        if (item.childrenMenus) {
            // 如果当前节点有子节点，则递归查找子节点
            const parentValues = getAllParentValues(item.childrenMenus, menuId);
            if (parentValues.length > 0) {
                // 如果找到了对应的父级menuId值，则将当前节点的menuId值添加到父级menuId值数组中
                parentValues.push(item.menuId);
                return parentValues;
            }
        }
        if (item.menuId === menuId) {
            // 如果当前节点的value值等于目标值，则返回当前节点的menuId值
            return [item.menuId];
        }
    }
    // 如果未找到对应的父级menuId值，则返回空数组
    return [];
}


// 使用递归处理 合并buttons按钮到chilMenus里面去
function mergeButtonsToChildren(data) {
    data.forEach((item) => {
        if (item.buttons && item.buttons.length > 0) {
            item.childrenMenus.push(...item.buttons);
            delete item.buttons;
        }
        if (item.childrenMenus && item.childrenMenus.length > 0) {
            mergeButtonsToChildren(item.childrenMenus);
        }
    });
    return data;
}

getMenuList()

</script>

<style lang='scss' scoped></style>